package com.twu.biblioteca.entity;

import org.fest.util.Strings;

public class Book extends Base {

  private final String title;
  private final String author;
  private final long isbn;
  private String publisher;
  private boolean available = true;

  public Book(long isbn, String title, String author) {
    if (isNotValidArgument(isbn, title, author)) {
      throw new IllegalArgumentException("Title and Author shall not be empty or null");
    }

    this.isbn = isbn;
    this.title = title;
    this.author = author;
  }

  public Book getBook(Book that) {
    Book clonedBook = new Book(that.getIsbn(), that.getTitle(), that.getAuthor());
    clonedBook.setAvailable(that.available);
    clonedBook.setPublisher(that.publisher);
    clonedBook.setUuid(that.getUuid());
    return clonedBook;
  }

  private boolean isNotValidArgument(long isbn, String title, String author) {
    return isInvalidIsbn(isbn)
        || Strings.isNullOrEmpty(title)
        || Strings.isNullOrEmpty(author);
  }

  private boolean isInvalidIsbn(long isbn) {
    return Long.valueOf(isbn).toString().length() != 10;
  }

  public long getIsbn() {
    return isbn;
  }

  public String getTitle() {
    return title;
  }

  public String getAuthor() {
    return author;
  }

  public boolean isAvailable() {
    return available;
  }

  public void setAvailable(boolean available) {
    this.available = available;
  }

  public String getPublisher() {
    return publisher;
  }

  public void setPublisher(String publisher) {
    this.publisher = publisher;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof Book)) {
      return false;
    }

    Book book = (Book) o;

    if (isbn != book.isbn) {
      return false;
    }
    if (author != null ? !author.equals(book.author) : book.author != null) {
      return false;
    }
    if (publisher != null ? !publisher.equals(book.publisher) : book.publisher != null) {
      return false;
    }
    if (title != null ? !title.equals(book.title) : book.title != null) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    int result = title != null ? title.hashCode() : 0;
    result = 31 * result + (author != null ? author.hashCode() : 0);
    result = 31 * result + (int) (isbn ^ (isbn >>> 32));
    result = 31 * result + (publisher != null ? publisher.hashCode() : 0);
    return result;
  }

  @Override
  public String toString() {
    return "Book{" +
        "title='" + title + '\'' +
        ", author='" + author + '\'' +
        ", isbn=" + isbn +
        ", publisher='" + publisher + '\'' +
        '}';
  }
}
